import HTTP from '@/api/login/index';
import { onMounted, ref } from 'vue';
import { userInfoObj } from '@/utils/types';
import { showToast } from '@/utils/messageTip';
import { getStorage, saveStorage, clearStorage } from '@/utils/uni-storage';
import { DOWNLOAD } from '@/constant/download';
// import checkUpdates from '@/uni_modules/uni-upgrade-center-app/utils/check-update.js';

export default function useIndex() {
    /**
     * download-model
     */
    const showModal = ref<boolean>(false);
    const downloadInfo = ref<Record<string, string | number>>({
        company: '',
        progress: 0,
    });

    /**
     * 展示信息
     */
    const userInfo = ref<userInfoObj>({
        account: '',
        userName: '',
        roles: '',
        version: '',
        versionCode: '',
        baseUrl: '',
    });

    /**
     * 打印机品牌
     */
    const printBrand = ref<string>('');

    /**
     * 退出登录
     */
    function handleLogout() {
        uni.showModal({
            content: '是否退出登录？',
            success: (res) => {
                if (res.confirm) {
                    confirmLogout();
                }
            },
        });
    }

    /**
     * 确认退出
     */
    async function confirmLogout() {
        const res = await HTTP.logout();

        if (res) {
            clearStorage();
            uni.reLaunch({ url: '/pages/login/index' });
        }
    }

    /**
     * 跳转到修改密码
     */
    function handleChangePassword() {
        uni.navigateTo({
            url: `/pages/setting/change-password`,
        });
    }

    /**
     * 检测更新
     */
    async function handleCheckUpdate() {
        const res = await HTTP.checkVersion();

        if (!res) {
            return;
        }

        if (
            userInfo.value.versionCode &&
            res.data.appVersion &&
            Number(userInfo.value.versionCode) < Number(res.data.appVersion)
        ) {
            uni.showModal({
                content: `当前 APP 版本号为 ${userInfo.value.versionCode ?? ''}，最新版本号为 ${
                    res.data.appVersion ?? ''
                }，是否下载最新版本？`,
                success: (res) => {
                    if (res.confirm) {
                        // #ifdef APP-PLUS
                        confirmUpdate();
                        // #endif
                    }
                },
            });
        } else {
            showToast('暂无更新');
        }
    }

    /**
     * 确认更新
     */
    async function confirmUpdate() {
        // try {
        //     await checkUpdates();
        // } catch (error: any) {
        //     showToast(error.result.message);
        // }

        if (DOWNLOAD.hasOwnProperty(userInfo.value.baseUrl)) {
            download(DOWNLOAD[userInfo.value.baseUrl][0], DOWNLOAD[userInfo.value.baseUrl][1]);
        } else {
            showToast('当前环境暂无更新');
        }
    }

    /**
     * 下载安装
     */
    async function download(company: string, url: string) {
        downloadInfo.value.company = company;
        showModal.value = true;

        const downloadTask = uni.downloadFile({
            url,
            success: (res) => {
                if (res.statusCode === 200) {
                    plus.runtime.install(
                        // 需要安装的文件路径
                        res.tempFilePath,
                        // 应用安装设置的参数
                        {
                            force: true,
                        },
                        // 安装成功的回调
                        function () {
                            plus.runtime.restart();
                        },
                        // 安装失败的回调
                        function (err) {
                            console.log('install-failed：' + err);
                        }
                    );
                }
            },
            fail(err) {
                console.log('download-failed：' + err);
            },
            complete() {
                showModal.value = false;
            },
        });

        // 监听下载进度
        downloadTask.onProgressUpdate((res) => {
            downloadInfo.value.progress = res.progress;
        });
    }

    /**
     * 组件挂载后
     */
    onMounted(() => {
        userInfo.value.account = getStorage('userInfo').account;
        userInfo.value.userName = getStorage('userInfo').userName;
        userInfo.value.roles = getStorage('userInfo').roles?.toString();
        userInfo.value.baseUrl = getStorage('baseUrl') || import.meta.env.VITE_API_URL;
        printBrand.value = getStorage('BrandAndLanguage').brand;

        // #ifdef APP-PLUS
        plus.runtime.getProperty(plus.runtime.appid as string, (wgtinfo) => {
            userInfo.value.version = wgtinfo.version as string;
            userInfo.value.versionCode = wgtinfo.versionCode as string;
        });
        // #endif
    });

    return {
        userInfo,
        printBrand,
        showModal,
        downloadInfo,
        handleChangePassword,
        handleCheckUpdate,
        confirmUpdate,
        handleLogout,
        confirmLogout,
    };
}
